const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const { testConnection } = require('./config/database');
const path = require('path');
require('dotenv').config({ path: './config.env' });
try { require('dotenv').config({ path: path.join(__dirname, '../.env'), override: true }); } catch (e) {}
const axios = require('axios');
const analyticsRouter = require('./routes/analytics');

const app = express();
const PORT = process.env.PORT || 5000;

// 安全中间件
app.use(helmet());

// 限流中间件
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100 // 限制每个IP 15分钟内最多100个请求
});
app.use(limiter);

// CORS配置
app.use(cors({
  origin: '*', // 允许所有来源
  credentials: true
}));

// 解析JSON和URL编码的请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use('/uploads', express.static('uploads'));

// 路由
app.use('/api/auth', require('./routes/auth'));
app.use('/funds', require('./routes/funds'));
app.use('/api/factors', require('./routes/factors'));
app.use('/api/strategies', require('./routes/strategies'));
app.use('/api/portfolios', require('./routes/portfolios'));
app.use('/api/trades', require('./routes/trades'));
app.use('/api/users', require('./routes/users'));
app.use('/api/analytics', analyticsRouter);

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({ 
    status: 'OK', 
    timestamp: new Date().toISOString(),
    message: '智能投顾系统后端API运行正常'
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({ message: '接口不存在' });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ 
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : {}
  });
});

// 启动服务器
const startServer = async () => {
  try {
    // 测试数据库连接（可通过环境变量跳过）
    if (process.env.SKIP_DB_CHECK === 'true') {
      console.log('⚠️ 跳过数据库连接检查（SKIP_DB_CHECK=true）');
    } else {
      await testConnection();
    }
    
    // 启动服务器
    app.listen(PORT, () => {
      console.log(`🚀 服务器运行在端口 ${PORT}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/api/health`);
      console.log(`🔗 API文档: http://localhost:${PORT}/api`);
    });
  } catch (error) {
    console.error('❌ 服务器启动失败:', error);
    process.exit(1);
  }
};

startServer();

module.exports = app; 

app.get('/api/proxy/lenovo', async (req, res) => {
  try {
    const axios = require('axios');
    const response = await axios.get('https://dsp.lenovo.com.cn/lenovo/bid?clientType=api&positionId=50296');
    res.json(response.data);
  } catch (error) {
    res.status(500).json({ message: '代理请求失败' });
  }
});